
// Make connection when DOM has finished loading
$(document).ready(ConnectToChat);

//------------------------------------------------------------------------------
function ConnectToChat()
{
  // Open connection 
  $('#postit').prop('disabled', 'disabled');
  $('#debugmessage').text('Connecting...');
  //var pusher = new Pusher('90970d90c5a425dc647e');
  var pusher = new Pusher('90970d90c5a425dc647e', {encrypted:true});

  // Check connection status
  pusher.connection.bind('connected', function()
  {
    $('#postit').removeProp('disabled');
    $('#debugmessage').text('Connected!').fadeOut(2000);
  });  

  // Create channel  
  var myChannel = pusher.subscribe('chat-channel'); 
  
  // Bind event to function
  myChannel.bind('new-message', 
    function(data) 
    {
      $('#messages').append(data);
      $("#messages").prop({ scrollTop: $("#messages").prop("scrollHeight") });
    });
    
    // Bind enter key to post message
    $('#yourmessage').bind('keypress', function(e) {
            if(e.keyCode==13){
                    SendNewMessage();
            }
    });
    
    // Bind button click to post message
    $('#postit').click(SendNewMessage);
    
 }

//------------------------------------------------------------------------------
function SendNewMessage()
{
  // Read name and message from form       
  var name = $('#yourname').val();
  var message = $('#yourmessage').val();
  var connecting = $('#postit').prop('disabled');

  // Validate input
  if(name=='')
    name="Anonymous";
  
  // Are we still connecting?
  if(connecting)
    exit;
      
  if(message!='')
  {
    // Clear message
    $('#yourmessage').val('');
    
    // Send message to server
    $.ajax({
      url: "http://mi-linux.wlv.ac.uk/~in9352/websockets/push-event.php",
      type: "POST",
      data: ({name : name, message : message})
      });
  }
    
  // Refocus on text input ready for next message  
  $('#yourmessage').focus();

}
//------------------------------------------------------------------------------